// 导入 Vue 的响应式 API，包括 ref 和 computed
import {ref, computed} from 'vue'
// 导入 Pinia 的 defineStore 方法，用于定义状态管理 store
import {defineStore} from 'pinia'
// 导入封装的请求模块，用于发送 HTTP 请求
import request from '@/utils/request'
// 导入 User 类型定义，用于类型检查
import type {User, ApiResponse} from '@/types/user'
// 导入路由实例，用于重定向
import router from '@/router'

interface LoginForm {
    username: string  // 用户名
    password: string // 密码
}

interface RegisterForm {
    username: string
    password: string
    email?: string // 邮箱, 可选
    phonenumber?: string // 手机号, 可选
}

interface UpdateProfileForm {
    email?: string
    phonenumber?: string
    nickname?: string
    gender?: string
    birthday?: string
    bio?: string
}

interface ChangePasswordForm {
    oldPassword: string
    newPassword: string
    confirmPassword: string
}

// 用户管理相关接口
interface UserManagementForm {
    username: string
    email?: string
    first_name?: string
    password?: string
    is_active?: boolean
    role?: string  // 新增角色字段
}

interface UserListParams {
    page?: number
    page_size?: number
    username?: string
    email?: string
    status?: string
}

interface UserListResponse {
    results: User[]
    count: number
    page: number
    page_size: number
    total_pages: number
}

interface RegisterResponseData {
    token: string
    user: User
}

export const useUserStore = defineStore('user', () => {
    // 状态
    // 用户信息响应式变量，初始值为null
    const user = ref<User | null>(null)
    // 认证令牌响应式变量，从localStorage中获取初始值
    const token = ref<string | null>(localStorage.getItem('token'))
    // 计算属性，用于判断用户是否已登录（基于token是否存在）
    const isLoggedIn = computed(() => !!token.value)
    // 计算属性，用于判断用户是否已完全认证（既有token又有用户信息）
    const isAuthenticated = computed(() => !!token.value && !!user.value)

    // 登录
    const login = async (loginForm: LoginForm) => {
        try {
            const response = await request.post('/user/login/', loginForm) as ApiResponse<{token: string, user: User}>
            if (response.code === 200 && response.data) {
                const {token: jwtToken, user: userInfo} = response.data
                token.value = jwtToken
                user.value = userInfo
                localStorage.setItem('token', jwtToken)

                return {success: true, message: response.message}
            } else {
                return {success: false, message: response.message}
            }
        } catch (error: any) {
            return {
                success: false,
                message: error.message || '登录失败，请稍后重试'
            }
        }
    }

    // 恢复登录状态
    const restoreLoginState = async () => {
        const savedToken = localStorage.getItem('token')
        if (savedToken) {
            try {
                token.value = savedToken
                // 尝试获取用户信息验证token有效性
                if (!user.value) {
                    await fetchUserInfo()
                }
                console.log('恢复登录状态成功')
                return true
            } catch (error: any) {
                console.error('恢复登录状态失败:', error)
                // 只在401认证失败时清除token，其他错误保留token
                if (error?.response?.status === 401) {
                    console.log('认证失败，清除认证信息')
                    clearAuth()
                    throw error
                } else {
                    // 网络错误或其他临时错误，保留token允许用户重试
                    console.log('网络错误或临时错误，保留token')
                    return false
                }
            }
        }
        return false
    }

    /**
     * 用户注册函数
     * @param registerForm - 注册表单数据，包含用户注册所需的信息
     * @returns Promise对象，包含注册结果信息，格式为{success: boolean, message: string}
     */
    const register = async (registerForm: RegisterForm) => {
        try {
            console.log("registerForm:", registerForm)
            // 发送注册请求到服务器
            const response = await request.post('/user/register/', registerForm) as ApiResponse<RegisterResponseData>
            // 根据服务器返回的状态码判断注册是否成功
            if (response.code === 200) {
                console.log("response:", response)
                return {success: true, message: response.message}
            } else {
                console.log("response:", response)
                return {success: false, message: response.message}
            }
        } catch (error: any) {
            console.log("response_error:", error)
            // 处理注册过程中出现的异常情况
            return {
                success: false,
                message: error.message || '注册失败，请稍后重试'
            }
        }
    }

    // 登出
    const logout = () => {
        if (token.value) {
            localStorage.removeItem('token')
            user.value = null
            token.value = null
            router.push('/login')
        }
    }

    // 获取用户信息（用于token验证）
    const fetchUserInfo = async () => {
        try {
            const response = await request.get('/user/info/') as ApiResponse<User>
            console.log('获取用户信息response:', response)
            if (response.code === 200 && response.data) {
                user.value = response.data
                return response.data
            } else {
                throw new Error(response.message || '获取用户信息失败')
            }
        } catch (error: any) {
            console.error('获取用户信息失败:', error)
            throw error
        }
    }

    // 获取当前用户详细信息和角色
    const fetchUserProfile = async () => {
        try {
            const response = await request.get('/user/profile/') as ApiResponse<User & { roles: string[] }>
            console.log('获取用户详细信息response:', response)
            if (response.code === 200 && response.data) {
                // 更新用户信息，包含角色信息
                user.value = { ...user.value, ...response.data }
                return response.data
            } else {
                throw new Error(response.message || '获取用户详细信息失败')
            }
        } catch (error: any) {
            console.error('获取用户详细信息失败:', error)
            throw error
        }
    }

    // 清除认证信息
    const clearAuth = () => {
        localStorage.removeItem('token')
        user.value = null
        token.value = null
    }

    // 更新个人信息
    const updateProfile = async (profileData: UpdateProfileForm) => {
        try {
            console.log('发送个人信息更新请求:', profileData)
            const response = await request.put('/user/profile/update/', profileData) as ApiResponse<User>
            console.log('个人信息更新响应:', response)
            
            if (response.code === 200 && response.data) {
                user.value = response.data
                return { success: true, message: response.message }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            console.error('个人信息更新失败:', error)
            console.error('错误详情:', error.response)
            
            // 获取更详细的错误信息
            let errorMessage = '更新失败，请稍后重试'
            if (error.response && error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message
            } else if (error.message) {
                errorMessage = error.message
            }
            
            return {
                success: false,
                message: errorMessage
            }
        }
    }

    // 修改密码
    const changePassword = async (passwordData: ChangePasswordForm) => {
        try {
            const response = await request.put('/user/password/change/', passwordData) as ApiResponse
            if (response.code === 200) {
                return { success: true, message: response.message }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            return {
                success: false,
                message: error.message || '密码修改失败，请稍后重试'
            }
        }
    }

    // 上传头像
    const uploadAvatar = async (file: File) => {
        try {
            const formData = new FormData()
            formData.append('avatar', file)
            
            const response = await request.post('/user/avatar/upload/', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }) as ApiResponse<{ avatar: string }>
            
            if (response.code === 200 && response.data) {
                // 更新用户头像
                if (user.value) {
                    user.value.avatar = response.data.avatar
                }
                return { success: true, message: response.message, avatar: response.data.avatar }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            return {
                success: false,
                message: error.message || '头像上传失败，请稍后重试'
            }
        }
    }

    // 上传Base64头像
    const uploadAvatarBase64 = async (avatarData: string) => {
        try {
            const response = await request.post('/user/avatar/upload/', {
                avatar_data: avatarData
            }) as ApiResponse<{ avatar: string }>
            
            if (response.code === 200 && response.data) {
                // 更新用户头像
                if (user.value) {
                    user.value.avatar = response.data.avatar
                }
                return { success: true, message: response.message, avatar: response.data.avatar }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            return {
                success: false,
                message: error.message || '头像上传失败，请稍后重试'
            }
        }
    }

    // 用户管理相关方法
    
    // 获取用户列表
    const getUserList = async (params: UserListParams) => {
        try {
            const response = await request.get('/user/management/list/', { params }) as ApiResponse<UserListResponse>
            if (response.code === 200 && response.data) {
                return { success: true, data: response.data, message: response.message }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            return {
                success: false,
                message: error.message || '获取用户列表失败，请稍后重试'
            }
        }
    }

    // 创建用户
    const createUser = async (userData: UserManagementForm) => {
        try {
            const response = await request.post('/user/management/create/', userData) as ApiResponse<User>
            if (response.code === 200 && response.data) {
                return { success: true, data: response.data, message: response.message }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            // 获取更详细的错误信息
            let errorMessage = '用户创建失败，请稍后重试'
            if (error.response && error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message
            } else if (error.message) {
                errorMessage = error.message
            }
            
            return {
                success: false,
                message: errorMessage
            }
        }
    }

    // 更新用户
    const updateUser = async (userId: number, userData: Partial<UserManagementForm>) => {
        try {
            const response = await request.put(`/user/management/${userId}/update/`, userData) as ApiResponse<User>
            if (response.code === 200 && response.data) {
                return { success: true, data: response.data, message: response.message }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            // 获取更详细的错误信息
            let errorMessage = '用户更新失败，请稍后重试'
            if (error.response && error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message
            } else if (error.message) {
                errorMessage = error.message
            }
            
            return {
                success: false,
                message: errorMessage
            }
        }
    }

    // 切换用户状态
    const toggleUserStatus = async (userId: number) => {
        try {
            const response = await request.patch(`/user/management/${userId}/toggle-status/`) as ApiResponse<User>
            if (response.code === 200 && response.data) {
                return { success: true, data: response.data, message: response.message }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            // 获取更详细的错误信息
            let errorMessage = '状态切换失败，请稍后重试'
            if (error.response && error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message
            } else if (error.message) {
                errorMessage = error.message
            }
            
            return {
                success: false,
                message: errorMessage
            }
        }
    }

    // 删除用户
    const deleteUser = async (userId: number) => {
        try {
            const response = await request.delete(`/user/management/${userId}/delete/`) as ApiResponse
            if (response.code === 200) {
                return { success: true, message: response.message }
            } else {
                return { success: false, message: response.message }
            }
        } catch (error: any) {
            // 获取更详细的错误信息
            let errorMessage = '用户删除失败，请稍后重试'
            if (error.response && error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message
            } else if (error.message) {
                errorMessage = error.message
            }
            
            return {
                success: false,
                message: errorMessage
            }
        }
    }

    return {
        user,
        token,
        isLoggedIn,
        isAuthenticated,
        login,
        register,
        logout,
        fetchUserInfo,
        fetchUserProfile,  // 新增：获取用户详细信息和角色
        clearAuth,
        restoreLoginState,
        updateProfile,
        changePassword,
        uploadAvatar,
        uploadAvatarBase64,
        // 用户管理相关方法
        getUserList,
        createUser,
        updateUser,
        toggleUserStatus,
        deleteUser,
    }
})
